using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

/// <summary>
/// File utils
/// </summary>
public class FileUtils
{
	/// <summary>
	/// Safely combines path parts
	/// </summary>
	/// <param name="pathParts"></param>
	/// <returns></returns>
	/// <remarks>Using separator='\'</remarks>
	public static string CombinePath(params string[] pathParts)
	{
		return CombinePath('\\', pathParts);
	}

	/// <summary>
	/// Safely combines path parts
	/// </summary>
	/// <param name="separator"></param>
	/// <param name="pathParts"></param>
	/// <returns></returns>
	public static string CombinePath(char separator, params string[] pathParts)
	{
		if (pathParts.Length == 0)
			return string.Empty;
		if (pathParts.Length == 1)
			return pathParts[0];
		int count = 0;
		for (int i = 0; i < pathParts.Length; i++)
		{
			if (pathParts[i] != null)
				count += pathParts[i].Length;
		}
		StringBuilder sb = new StringBuilder(count + pathParts.Length);
		bool first = true;
		char lastChar = ' ';
		for (int i = 0; i < pathParts.Length; i++)
		{
			if (string.IsNullOrEmpty(pathParts[i]))
				continue;
			if (first)
			{
				sb.Append(pathParts[i]);
				first = false;
			}
			else
			{
				char firstChar = pathParts[i][0];
				if ((lastChar == separator && firstChar != separator) ||
					 (lastChar != separator && firstChar == separator))
				{
					sb.Append(pathParts[i]);
				}
				else if (lastChar == separator && firstChar == separator)
				{
					sb.Append(pathParts[i], 1, pathParts[i].Length - 1);
				}
				else
				{
					sb.Append(separator);
					sb.Append(pathParts[i]);
				}
			}
			lastChar = pathParts[i][pathParts[i].Length - 1];
		}
		return sb.ToString();
	}
}
